package com;

import javax.servlet.http.HttpServletRequest;

import flex.messaging.FactoryInstance;
import flex.messaging.FlexContext;
import flex.messaging.FlexFactory;
import flex.messaging.config.ConfigMap;
import flex.messaging.services.ServiceException;



public class ManageBeanFactory implements FlexFactory {

	private static final String SOURCE = "source";

	public void initialize(String id, ConfigMap configMap) {
	}

	public FactoryInstance createFactoryInstance(String id, ConfigMap properties) {
		ManageBeanFactoryInstance instance = new ManageBeanFactoryInstance(this, id, properties);
		instance.setSource(properties.getPropertyAsString(SOURCE, instance
				.getId()));
		return instance;
	}

	public Object lookup(FactoryInstance inst) {
		ManageBeanFactoryInstance factoryInstance = (ManageBeanFactoryInstance) inst;
		return factoryInstance.lookup();
	}

	static class ManageBeanFactoryInstance extends FactoryInstance {
		ManageBeanFactoryInstance(ManageBeanFactory factory, String id, ConfigMap properties) {
			super(factory, id, properties);
		}

		public String toString() {
			return "ManageBeanFactory instance for id=" + getId() + " source="
					+ getSource() + " scope=" + getScope();
		}

		public Object lookup() {

                    HttpServletRequest hsr = FlexContext.getHttpRequest();
			String beanName = getSource();

			try {

                            //Object o = Prueba.getInstance();
				Object o = hsr.getSession().getAttribute(beanName);
				return o;
			} catch (Exception e) {
				ServiceException se = new ServiceException();
				String msg = "Java Bean '" + beanName + "' does not exist.";
				se.setMessage(msg);
				se.setRootCause(e);
				se.setDetails(msg);
				se.setCode("Server.Processing");
				throw se;
			}
		}
	}
}
